<?php

namespace app\queue\SmsSend;

use app\model\SmsLogModel;
use Hhink\WebmanSms\Sms as SmsPacket;
use app\model\mongo\SmsLogsMongo;
use Overtrue\EasySms\Exceptions\InvalidArgumentException;
use Overtrue\EasySms\Exceptions\NoGatewayAvailableException;
use support\facade\Logger;
use Webman\RedisQueue\Consumer;
use const support\SEND_SMS_QUEUE;

class SmsSend implements Consumer
{
    // 要消费的队列名
    public $queue = SEND_SMS_QUEUE;

    // 连接名
    public $connection = 'default';

    // 消费
    public function consume($data): bool
    {
        Logger::app('短信发送:开始','info',[$data['mobile']]);
        try {
            //短信发送
            $ret=SmsPacket::app()->send($data['mobile'], [
                'content' => sprintf(env('SMS_ACCESS_CONTENT'), $data['code']),
                'template' => env('SMS_ACCESS_TEMPLATE', ''),
                'data' => [
                    'code' => $data['code']
                ],
            ]);
        } catch (InvalidArgumentException | NoGatewayAvailableException $e) {
            Logger::app('短信发送:异常','info',[$e->getMessage()]);
        }
        //发送记录收录
        SmsLogModel::insertGetId([
            'mobile'    =>$data['mobile'],
            'code'      =>$data['code'],
            'result'    =>json_encode($ret??[]),
            'error'     =>isset($e)?$e->getMessage():''
        ]);
        return true;
    }
}
